<?php
/**
 *Administra los usuarios del sitio web
 *@author Luis Gabriel Rodriguez <luisgabriel84@gmail.com>
 */

/**
 *Administra los usuarios del sitio web
 */
class UsersController extends AppController {

	var $name = 'Users';
        /**
        * @var array
        * @access public
        */
	var $helpers = array('Html', 'Form');
        /**
        * @var array
        * @access public
        */
        var $components =array('Cookie','Email');


        /**
        * Configura la autenticacion de usuarios
        */

        function beforeFilter()
        {
           $this->layout='admin';
           $this->Auth->userScope = array('User.activo' => true);
           $this->Auth->loginError = "Nombre de usuario o clave errados";
           $this->Auth->authError = "No tiene privilegios para ingresar, Ingrese con su nombre de usuario y clave";
           $this->Auth->loginRedirect = array('controller'=>'products','action'=>'index','admin'=>'true');
           $this->Auth->allow('add');
        }

        /**
         *
         * Registra a un usuario en la base de datos
         */
	function add() {
                $this->layout='default';
		if (!empty($this->data)) {
			$this->User->create();
                        $this->data['User']['activo'] = 0;
                        $this->data['User']['access_level'] = 2;
                        $this->data['User']['nombre'] = up(trim($this->data['User']['nombre']));
                        $this->data['User']['apellidos'] = up(trim($this->data['User']['apellidos']));
                        $this->data['User']['username'] = trim($this->data['User']['username']);
			if ($this->User->save($this->data)) {
                                $this->Email->to =  'en.ruta@hotmail.com';//mail aqui
				$this->Email->replyTo = $this->data['User']['email'];
				$this->Email->from = 'Enruta Colombia'.' <info@enrutacolombia.com>';
				$this->Email->subject = 'Enruta Colombia, solicitud de vinculación';
				$mail =$this->data['User']['email'];
				//mail que se le envia al nuevo usuario
				$this->data['Contact']['message'] = 'Datos de usuario Solicitando vinculacion';
				$this->data['Contact']['message'].= "\r\n".'Nombres y apellidos:'.$this->data['User']['nombre']. ' ' .$this->data['User']['apellidos'];
				$this->data['Contact']['message'].= "\r\n".'Nombre de usuario: '.$this->data['User']['username'];
                                $this->data['Contact']['message'].= "\r\n".'Clave: '.$this->data['User']['password2'];
                                $this->data['Contact']['message'].= "\r\n".'Email: '.$this->data['User']['email'];
                                $this->data['Contact']['message'].= "\r\n".'Celular: '.$this->data['User']['celular'];
				$this->data['Contact']['message'].= "\r\n".'Fijo: '.$this->data['User']['fijo'];
				$this->data['Contact']['message'].= "\r\n".'Ciudad: '.$this->data['User']['ciudad'];
				$this->data['Contact']['message'].= "\r\n".'Direccion: '.$this->data['User']['direccion'];
				
				$this->Session->setFlash(__('Hemos recibido sus datos, nos pondremos en contacto con usted lo antes posible', true));
				
                                if($this->Email->send($this->data['Contact']['message']))
				{
					$this->redirect(array('action'=>'add'));
				}
			} 
                        else
                        {
				$this->Session->setFlash(__('Este usuario no puede ser guardado. Por favor trate de nuevo', true));
			}
		}
	}
        /**
         *
         * Modificar los datos de usuario
         */
	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

        /**
         * Ingreso
         */
        function __login()
        {
            $this->layout='login';

            	if ($this->Auth->user()) {

			$cookie = array();
			$cookie['username'] = $this->data['User']['username'];
			$cookie['password'] = $this->data['User']['password'];
			$this->Cookie->write('Auth.User', $cookie, true, '+1 weeks');
			unset($this->data['User']['remember_me']);


	}

		$cookie = $this->Cookie->read('Auth.User');
		if (!is_null($cookie)) {
			if ($this->Auth->login($cookie)) {
				//  Clear auth message, just in case we use it.
				$this->Session->del('Message.auth');
				$this->redirect($this->Auth->redirect());
			} else { // Delete invalid Cookie
				$this->Cookie->del('Auth.User');
			}
		}


        }
        
         /**
         * Autenticacion de usuarios
         */
        function admin_login()
        {
            $this->layout='login';
                        	if ($this->Auth->user()) {

			$cookie = array();
			$cookie['username'] = $this->data['User']['username'];
			$cookie['password'] = $this->data['User']['password'];
			$this->Cookie->write('Auth.User', $cookie, true, '+1 weeks');
			unset($this->data['User']['remember_me']);


	}

		$cookie = $this->Cookie->read('Auth.User');
		if (!is_null($cookie)) {
			if ($this->Auth->login($cookie)) {
				//  Clear auth message, just in case we use it.
				$this->Session->del('Message.auth');
				$this->redirect($this->Auth->redirect());
			} else { // Delete invalid Cookie
				$this->Cookie->del('Auth.User');
			}
		}



        }
         /**
         * Cerrar la session
         */
        function admin_logout()
        {
            $this->redirect($this->Auth->logout());
        }
        /**
         * Cerrar la session
         */
        function logout()
        {
            $this->Session->setFlash('Ha salido satisfactoriamente');
            $this->redirect($this->Auth->logout());
        }
         /**
         * Listado de usuarios registrados del sitio
         */
	function admin_index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

        /**
         * Ver los datos del usuario
         * @param integer id Identificador del usuario
         *
         */
	function admin_view($id = null)
        {
		if (!$id)
                {
			$this->Session->setFlash(__('Invalid User.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}
        /**
        * Agregar un nuevo usuario
        */
	function admin_add()
        {

		if (!empty($this->data)) {
			$this->User->create();
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
	}

        /**
         * Modificar usuario
         * @param integer $id Identificador del usuario
         */
	function admin_edit($id = null)
        {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}
         /**
         * Borrar usuario
         *@param integer $id Identificador del usuario
         */
	function admin_delete($id = null) {
		if (!$id)
                {
			$this->Session->setFlash(__('Invalid id for User', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->del($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>